package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 结算
 */
@Controller
public class TradeController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderFeignClient orderFeignClient;
    //结算
    @GetMapping("/trade.html")
    public String trade(Model model){

        //1:用户地址集合  用户微服务
        List<UserAddress> userAddressList = userFeignClient.getUserAddressList();
        model.addAttribute("userAddressList",userAddressList);
        //2:购物车选中集合  购物车微服务
        List<CartInfo> cartInfoListByChecked = cartFeignClient.
                findCartInfoListByChecked();

        //订单详情集合
        List<OrderDetail> orderDetailList = cartInfoListByChecked.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            //同属性数据传递
            BeanUtils.copyProperties(cartInfo,orderDetail);
            //ID 删除
            orderDetail.setId(null);//表示不使用购物车ID  使用订单详情自己生成ID
            //订单价格  取自于购物车中实实价格
            orderDetail.setOrderPrice(cartInfo.getSkuPrice());
            return orderDetail;
        }).collect(Collectors.toList());
        model.addAttribute("detailArrayList",orderDetailList);
        //3:小计 stream
        //商品数量
        long totalNum = orderDetailList.stream().collect(
                Collectors.summarizingInt(OrderDetail::getSkuNum)).getSum();
        //总金额
        double totalAmount = orderDetailList.stream().collect(
                Collectors.summarizingDouble(orderDetail -> {

                    //原来的写法 错误
//                    return orderDetail.getOrderPrice().doubleValue()*orderDetail.getSkuNum();
                    return  orderDetail.getOrderPrice(). //Integer 可以自动拆箱 int
                            multiply(new BigDecimal(orderDetail.getSkuNum())).
                            doubleValue();
                })).getSum();
        model.addAttribute("totalNum",totalNum);
        model.addAttribute("totalAmount",totalAmount);
        //5:生成订单号
        String tradeNo = orderFeignClient.tradeNo();
        model.addAttribute("tradeNo",tradeNo);
        return "order/trade";
    }
}
